<template>
  <div>
    <van-cell-group inset>
      <van-field
        v-model:value="updateTeamForm.name"
        name="pattern"
        label="队伍名称:"
        placeholder="请输入队伍名称"
        :rules="[{ validator: validatorMessage }]"
        @change="changeInput($event, 'name')"
      />
      <van-cell title="队伍头像">
        <van-image
        v-if="tempFile"
            width="50px"
            height="50px"
            fit="cover"
            :src="tempFile"
            @click="selectImg"
          />
      </van-cell>
      <van-field
        v-model:value="updateTeamForm.description"
        rows="2"
        autosize
        label="队伍描述:"
        type="textarea"
        maxlength="500"
        placeholder="请输入队伍描述"
        show-word-limit
        :rules="[{ validator: validatorMessage }]"
        @change="changeInput($event, 'description')"
      />

      <van-field
        name="stepper"
        label="最大人数"
        
      >
        <template #input>
          <van-stepper :value="updateTeamForm.maxNum" max="10" min="3" @change="changeInput($event, 'maxNum')" />
        </template>
      </van-field>
      <div @click="showPopup">
        <van-field
          v-model:value="updateTeamForm.expireTime"
          readonly
          label="过期时间:"
          type="text"
          is-link
          placeholder="请选择过期时间"
          :rules="[{ validator: validatorMessage }]"
        />
      </div>

      <van-field name="radio" label="队伍状态">
        <template #input>
          <van-radio-group
            :value="updateTeamForm.status"
            direction="horizontal"
            @change="changeInput($event, 'status')"
          >
            <van-radio name="0">公开</van-radio>
            <van-radio name="1">私有</van-radio>
            <!-- <van-radio name="2">加密</van-radio> -->
          </van-radio-group>
        </template>
      </van-field>
      <van-field  label="是否修改密码" v-if="Number(updateTeamForm.status) === 2">
        <template #button>
          <van-switch :checked="pwdSwitch" size="20px" @change="onChangePwdSwitch" />
        </template>
      </van-field>

      <van-field
        v-if="(Number(updateTeamForm.status) === 2&&pwdSwitch)"
        v-model="updateTeamForm.password"
        type="password"
        name="password"
        label="原密码"
        placeholder="请输入原密码"
        :rules="[{ required: true, message: '请填写密码' }]"
        @change="changeInput($event, 'password')"
      />
      
      <van-field
        v-if="(Number(updateTeamForm.status) === 2&&pwdSwitch)"
        v-model="updateTeamForm.newPassword"
        type="password"
        name="password"
        label="新密码"
        placeholder="请输入新密码"
        :rules="[{ required: true, message: '请填写密码' }]"
        @change="changeInput($event, 'password')"
      />
      <van-field
        v-if="(Number(updateTeamForm.status) === 2&&pwdSwitch)"
        v-model="updateTeamForm.checkPassword"
        type="password"
        name="password"
        label="新密码"
        placeholder="再次输入新密码"
        :rules="[{ required: true, message: '请填写密码' }]"
        @change="changeInput($event, 'password')"
      />
    </van-cell-group>

    <!-- 时间日期选择 -->
    <van-popup :show="show" position="bottom" custom-style="height: 50%;">
      <van-datetime-picker
        type="datetime"
        :value="currentDate"
        :min-date="minDate"
        :max-date="maxDate"
        @input="onInput"
        @confirm="confirmDate"
        @cancel="closePopup"
      />
    </van-popup>

    <div style="margin: 16px">
      <van-button
        round
        block
        type="primary"
        native-type="submit"
        @click="submitData()"
      >
        提交
      </van-button>
    </div>
  </div>
  <van-notify id="van-notify" />
</template>
<script setup>
import { ref, reactive,onMounted } from 'vue'
import { parseTime } from '../utils/dateTimeFormat'
import { createTeam, updateTeam } from '../api/team/team'
import useStore from '../store';
import {searchTeam} from '../api/team/team'

let dateObj = ref({
  minHour: 10,
  maxHour: 20,
  minDate: new Date().getTime(),
  maxDate: new Date(2099, 12, 31).getTime(),
  currentDate: new Date().getTime(),
})
let updateTeamForm = ref({
  name: '',
  url:'',
  maxNum: 3,
  description: '',
  expireTime: '',
  password: '',
  status: '0',
})

let show = ref(false) //展示时间选择器
let pwdSwitch=ref(false) //是否修改队伍密码
const minHour = ref(10)
const maxHour = ref(20)
const minDate = ref(new Date().getTime())
const maxDate = ref(new Date(2099, 12, 31).getTime())
const currentDate = ref(new Date().getTime())
const tempFile=ref(updateTeamForm.value.url)



// 校验函数可以直接返回一段错误提示
const validatorMessage = (val) => {
  if (val === null || val === '') {
    return '不能为空'
  }
  return true
}





//提交数据
const submitData = async () => {
  console.log(updateTeamForm.value)
  console.log(tempFile.value.slice(0,11))
  if(tempFile.value.slice(0,11)==='http://tmp/'||tempFile.value.slice(0,11)==='wxfile://tm'){
    await upload()
  }
  const res = await updateTeam(updateTeamForm.value)
  console.log(res)
  uni.showToast({
    title: '修改成功',
    icon: 'success',

  })
  // 1. 获取当前页面栈实例（此时最后一个元素为当前页）
  let pages = getCurrentPages() 
     
     // 2. 上一页面实例
     	// 注意是length长度，所以要想得到上一页面的实例需要 -2
     	// 若要返回上上页面的实例就 -3，以此类推
     let prevPage = pages[pages.length -2] 
     console.log(prevPage);

  setTimeout(()=>{
    uni.navigateBack({
    delta: 1,
    success:()=>{
      // 3. 给上一页面实例绑定)方法和参数（注意是$vm）
    //  prevPage.$vm.getCreateTeamList()
    }
  })
  },1500)
  
}
const showPopup = () => {
  show.value = true
}
//时间选择器
const onInput = ($event) => {
  console.log('11:',$event)

  
}
//选中时间确定
const confirmDate = ($event) => {
  console.log($event)
  const seletedTime = parseTime($event.detail, '{y}-{m}-{d} {h}:{i}:{s}')
  console.log(seletedTime)
  updateTeamForm.value.expireTime = seletedTime
  console.log(updateTeamForm.value);
  
  // currentDate.value=seletedTime
  show.value = false
}

//关闭弹窗
const closePopup = () => {
  show.value = false
}
//
const changeInput = (e, keyWord) => {
  let map = new Map([
    [
      'name',
      (detail) => {
        updateTeamForm.value.name = detail
      },
    ],
    [
      'description',
      (detail) => {
        updateTeamForm.value.description = detail
      },
    ],
    [
      'maxNum',
      (detail) => {
        updateTeamForm.value.maxNum = detail
      },
    ],
    [
      'password',
      (detail) => {
        updateTeamForm.value.password = detail
      },
    ],
    [
      'status',
      (detail) => {
        updateTeamForm.value.status = detail
      },
    ],
  ])
  const handeler = map.get(keyWord)
  if (handeler) {
    handeler(e.detail)
  } else {
    console.log('没找到该函数')
  }
}
const getTeamInfo= async()=>{
  const res=await searchTeam({id:useStore().team().teamUpdateID})
  console.log(res);
  updateTeamForm.value=res.data.teamUserVOList[0]
  updateTeamForm.value={
    id:res.data.teamUserVOList[0].id,
    name: res.data.teamUserVOList[0].name,
    url:res.data.teamUserVOList[0].url,
    maxNum: res.data.teamUserVOList[0].maxNum,
    description: res.data.teamUserVOList[0].description,
    expireTime: res.data.teamUserVOList[0].expireTime,
    password: res.data.teamUserVOList[0].password,
    status: res.data.teamUserVOList[0].status+"",
  }
  tempFile.value=updateTeamForm.value.url
  updateTeamForm.value.status+=""
  console.log(updateTeamForm.value);
  
  
  
  
}
const onChangePwdSwitch=(e)=>{
  pwdSwitch.value=e.detail
}
//选择照片
const selectImg=()=>{
  uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
        success: function (res) {
          console.log(res);
          
            console.log(JSON.stringify(res.tempFilePaths[0]));
            tempFile.value=res.tempFiles[0].path
            console.log(tempFile.value);
            
        }
    });
}
//上传
const upload=()=>{
  return new Promise((resolve,reject)=>{
    uni.uploadFile({
                url:'https://www.pickteams.cn/api/team/upload',
                filePath:tempFile.value,
                name: 'file',
                header:{
                    "Authorization":uni.getStorageSync('Authorization'),
                    "content-type":"utf-8"
                },
                success: (uploadFileRes) => {
                    console.log(uploadFileRes.data);
                    const result=JSON.parse(uploadFileRes.data)
                    if(result.code===0){
                      updateTeamForm.value.url=result.data
                        resolve(result)
                    }else{
                        uni.showToast({
                            title:'上传失败',
                            icon:'fail'


                        })
                        reject("上传失败")
                    }
                }
            })
  })
}
//生命周期
onMounted(()=>{
  getTeamInfo()
  console.log(useStore().team().teamUpdateID);
  
})
</script>
<style scoped></style>
